const express=require('express');
const serveStatic=require('serve-static');
const bodyParser=require('body-parser');
const session=require('express-session');
const multipart=require('connect-multiparty');
const path=require('path');
module.exports=function (done) {
	const debug=$.createDebug('init:express');
	debug('initing Express...');
	const app=express();
	app.use(bodyParser.urlencoded({extended: true}));
	app.use(bodyParser.json());
	app.use(multipart());
	app.use(session({
		secret: $.config.get('web.session.secret'),
		resave: true,
		saveUninitialized:true
	}));
	app.use(function (req,res,next) {
		res.success=function (result) {
			res.json({success:true,result});
		}
		next();
	});
	const router=express.Router();
	const routerWrap={};
	['get','post','head','put','delete','options'].forEach(method => {
		routerWrap[method]=function (path,...fnList) {
			fnList=fnList.map(fn => {
				return function (req,res,next) {
					const ret=fn(req,res,next);
					//if (ret.catch)
					//	ret.catch(next);
				}
			});
			router[method](path,...fnList);
		}
	});
	$.router=routerWrap;
	app.use(router);
	app.use('/static',serveStatic(path.resolve(__dirname,'../../static')));
	app.listen($.config.get('web.port'),err => {
		done(err);
		debug('server started!');
	});

}